package com.ruoyi.project.thirdservice.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.RedisKeyConfigure;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.thirdservice.service.wx.WxAuthCode2SessionService;
import com.ruoyi.project.thirdservice.service.wx.entity.session.WxUserSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yan
 */
@RestController
@RequestMapping("wx-api-sns")
public class WxAuthCallbackController {

    private static Logger logger = LoggerFactory.getLogger(WxAuthCallbackController.class);

    @Value("${wx-api.sns.appid}")
    private String appid;
    @Value("${wx-api.sns.secret}")
    private String secret;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private WxAuthCode2SessionService wxAuthCode2SessionService;

    /**
     * WX通过code换取session + openid
     *
     * @param jscode
     * @return
     */
    @RequestMapping(value = "/jscode2session", method = RequestMethod.GET)
    public AjaxResult getData(@RequestParam("code") String jscode) {
        Object data = this.wxAuthCode2SessionService.getData(appid, secret, jscode);

        // 此处已经能获取用户的sessionId等敏感信息
        logger.warn(">>> Get User Session ==> {}", JSON.toJSONString(data));
        WxUserSession session = JSON.parseObject((String) data, WxUserSession.class);

        this.redisCache.setCacheObject(RedisKeyConfigure
                .genWxSessionKey(session.getOpenid()), session);

        return AjaxResult.success(session);
    }
}
